/**
 *
 * 用户登录接口
 *
 */
const rootPath = '../../../';
const router = require('express').Router();
const baseTool = require(rootPath + 'common/base-tool');
const tips = require(rootPath + 'common/tips');
const log = require(rootPath + 'common/log');
const CURD = require(rootPath + 'compontents/DB/CURDClass')
const RSA = require(rootPath + 'common/RSAClass');
const baseRole = require(rootPath + 'common/base-role')
const md5 = require('md5-node');

router.post('/login', async (req, res, next) => {
    log.api('user api login');

    /**
     * =======================
     *   自动登录
     * =======================
     */
    let xhtk = req.cookies.xhtk;
    let uid = req.cookies.uid;
    // console.log('cookie-uid: ', uid);
    // console.log('cookie-xhtk: ', xhtk);
    if (xhtk && uid) {
        // 解密
        try {
            xhtk = await new RSA().decrypt(xhtk);
            const token = xhtk.split('_XHPX_')[1];
            const login_rows = await CURD.select({
                fields: 'id',
                table: 'user',
                where: [
                    {
                        wfield: 'uid',
                        wvalue: uid,
                    },
                    {
                        wfield: 'token',
                        wvalue: token
                    }
                ]
            });
            if (login_rows.length) {
                // 已注册
                getUserInfo(uid).then( hasInfo => {
                    resultData(res, hasInfo)
                })
            } else {
                // 将角色添加到在线玩家列表
                baseRole.add_online(uid);

                res.cookie('uid', 0, {signed: false, maxAge: 0});
                res.cookie('xhtk', 0, {signed: false, httpOnly: true, maxAge: 0});
                res.json({
                    code: tips.loginCookie.failCode,
                    msg: tips.loginCookie.fail
                })
            }
        } catch (err) {
            log.err(err);
        }
        return;
    }

    const r = req.body;
    const uname = r.uname;
    const password = r.pwd;
    console.log(r)


    // 账号、密码格式验证
    if (!uname) {
        res.json({
            code: tips.uname.emptyCode,
            msg: tips.uname.emport
        })
        return;
    }
    if (!password) {
        res.json({
            code: tips.pwd.emptyCode,
            msg: tips.pwd.emport
        })
        return;
    }
    if (!baseTool.verifyName(uname)) {
        console.log(tips.uname.format);
        res.json({
            code: tips.uname.formatCode,
            msg: tips.uname.format
        })
        return;
    }

    if (!baseTool.verifyPwd(password)) {
        res.json({
            code: tips.pwd.formatCode,
            msg: tips.pwd.format
        })
        return;
    }


    /**
     * =======================
     *   账号密码登录
     * =======================
     */
    try {
        const login_rows = await CURD.select({
            fields: 'id, uid, token',
            table: 'user',
            where: [
                {
                    wfield: 'username',
                    wvalue: uname,
                },
                {
                    wfield: 'password',
                    wvalue: md5(password)
                }
            ]
        })

        if (login_rows.length) {
            const id = login_rows[0].id;
            const token = login_rows[0].token;
            const uid = login_rows[0].uid;

            // 公钥加密
            const t = id +'_XHPX_'+ token.toString();
            const publicKey = await new RSA().encrypt(t);

            //创建cookie对象
            res.cookie('uid', uid, {signed: false, maxAge: global.COOKIE_TIME});
            res.cookie('xhtk', publicKey, {signed: false, httpOnly: true, maxAge: global.COOKIE_TIME});

            // 已注册
            getUserInfo(uid).then( hasInfo => {
                resultData(res, hasInfo)
            })
        } else {
            // 将角色添加到在线玩家列表
            baseRole.add_online(uid);

            res.send({
                code:tips.login.failCode,
                msg:tips.login.fail
            })
        }
    } catch (e) {
        console.log(e)
        res.json({
            code: tips.sql.selectFailCode,
            msg: tips.sql.selectFail
        })
    }
});

// 返回数据
function resultData (res, hasInfo) {
    if (typeof hasInfo=='number') {
        // 有角色信息
        let resData = {
            code: tips.successCode,
            msg: tips.success,
        }
        // -1, 无角色信息
        // 0, 有角色信息，请设置天赋
        // 1, 有天赋，已出生
        resData.status = parseInt(hasInfo)
        res.json(resData)
    } else {
        // 无角色信息
        res.json({
            code: tips.successCode,
            msg: tips.success,
            status: -1
        })
    }
}

// 账号已经注册，查询是否有角色信息
async function getUserInfo(uid) {
    const user_info_rows = await CURD.select({
        fields: '`id`,`character`',
        table: 'user_info',
        where: [
            {
                wfield: 'uid',
                wvalue: uid,
            }
        ]
    })

    if (user_info_rows.length) {
        return user_info_rows[0].character;
    } else {
        return false;
    }
}

module.exports = router;